package com.example.administrator.appstpremvpdemo.helper;

import android.app.Activity;
import android.graphics.Bitmap;

import com.example.administrator.appstpremvpdemo.common.Constances;
import com.example.administrator.appstpremvpdemo.common.MainApplication;
import com.example.administrator.appstpremvpdemo.net.HttpListener;
import com.example.administrator.appstpremvpdemo.net.HttpResponseListener;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * @Author Administrator
 * @Date 2017/12/12
 * @description
 * @function
 */

public class SplashImageHelper {

    private Activity mActivity;

    public SplashImageHelper(Activity activity) {
        this.mActivity = activity;
    }

    /**
     * 请求网络获取图片，当本地有缓存时，就加载缓存图片，没有缓存就请求网络
     */
    public void preLoadSpashImage() {
        Request<Bitmap> imageRequest = NoHttp.createImageRequest(Constances.URL_SPALASH_IMG);
        //设置缓存的key为图片的url
        imageRequest.setCacheKey(Constances.URL_SPALASH_IMG);
        //缓存中没有的时候才会去请求网络获取图片
        imageRequest.setCacheMode(CacheMode.NONE_CACHE_REQUEST_NETWORK);
        MainApplication.getmRequestQueue()
                .add(0, imageRequest, new HttpResponseListener<Bitmap>(imageRequest, new HttpListener<Bitmap>() {
                    @Override
                    public void onSucceed(int what, Response<Bitmap> response) {
                        if (response != null) {
                            Bitmap bitmap = response.get();
                            boolean fromCache = response.isFromCache();//是否来自缓存
                            mIGetSplashImage.getSplashBitmap(bitmap, fromCache);
                        }
                    }

                    @Override
                    public void onFailed(int what, Response<Bitmap> response) {

                    }
                }));
    }

    private IGetSplashImageListener mIGetSplashImage;

    public void setIGetSplashImage(IGetSplashImageListener IGetSplashImage) {
        mIGetSplashImage = IGetSplashImage;
    }

    /**
     * 请求网络获取后成功的回到
     */
    public interface IGetSplashImageListener {
        /**
         * 获取到缓存或者新下载的图片
         * @param bitmap
         * @param fromCache 是否来自缓存
         */
        void getSplashBitmap(Bitmap bitmap, boolean fromCache);
    }
}
